<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;

class CodeController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        /*验证码*/
    //1.创建画布
    $w = 150;
    $h = 50;
    $path = public_path('/admin/css/msyhbd.ttf');
    // dd($path);
    $hImg = imagecreatetruecolor($w,$h);
    // $color = $this ->randColor();
    $color = imagecolorallocate($hImg,rand(128,255),rand(128,255),rand(128,255));
    $colors = imagecolorallocate($hImg,rand(0,127),rand(0,127),rand(0,127));
    //2.画画
    imagefill($hImg,0,0,$color);
    
    $str = '34567abcdefghijkmnprstuvwyxACDEFGHIJKLMNPQRSTUVWXY';
    
    $str = str_shuffle($str); //打乱原有字符串
    $code = substr($str,0,4); //截取4位字符
    session(['code' => $code]);
    for($i=0;$i<4;$i++){
    //参数: 画布资源,大小,角度,x,y,颜色,字体文件,内容
       imagettftext($hImg,18,rand(-30,30),18+30*$i,30,$colors,'admin/css/msyhbd.ttf',$code[$i]);
    }
    
    //干扰点
    for($i=1;$i<=100;$i++){
       imagesetpixel($hImg,rand(0,$w),rand(0,$h),$colors);
    }
    //干扰线
    for($i=1;$i<=8;$i++){
       imageline($hImg,rand(0,$w),rand(0,$h),rand(0,$w),rand(0,$h),$colors);
    }
    
    
    //3.输出到页面
    header('Content-type:image/jpeg');
    imagejpeg($hImg);
    
    // imagejpeg($hImg,'./xxoo.jpg'); 以文件的形式输出
    
    //4.释放资源
    imagedestroy($hImg);
    }
    
    public function randColor($flag=false)
    {
       global $hImg;
       if($flag){
          return imagecolorallocate($hImg,rand(0,127),rand(0,127),rand(0,127)); //深颜色
       }else{
          return imagecolorallocate($hImg,rand(128,255),rand(128,255),rand(128,255)); //浅颜色
       }
    }
}